package bll

import (
	"jgt-sdk/asapi"

	"github.com/spf13/viper"

	"github.com/pkg/errors"
)

// Login 登录管理
type Login struct {
	MenuBll     *Menu     `inject:""`
	UserTypeBll *UserType `inject:""`
	UserBll     *User     `inject:""`
	RoleBll     *Role     `inject:""`
}

// Verify 登录验证
func (a *Login) Verify(traceID, username, password string) (string, error) {
	userID, err := asapi.GetAPIWithTraceID(traceID).Login(&asapi.LoginRequest{
		UserName:  username,
		Password:  password,
		LoginType: 40,
	})
	if err != nil {
		return "", errors.Wrapf(err, "用户名或密码错误")
	}

	return userID, nil
}

// QuerySystemMenuByUserID 根据用户类型查询系统菜单
func (a *Login) QuerySystemMenuByUserID(userID, code string, hasActions ...bool) ([]map[string]interface{}, error) {
	userType := "10"
	user, _ := a.UserBll.Get(userID)
	if user != nil {
		userType = user.UserType
	}

	return a.QuerySystemMenuByUserType(userType, code, hasActions...)
}

// QuerySystemMenuByUserType 根据用户类型查询系统菜单
func (a *Login) QuerySystemMenuByUserType(userType, code string, hasActions ...bool) ([]map[string]interface{}, error) {
	var hasAction bool
	if len(hasActions) > 0 {
		hasAction = hasActions[0]
	}

	// 如果是超级管理员则返回全部数据
	if userType == viper.GetString("system_admin_user_type") {
		menus, err := a.MenuBll.QueryBySystemCode(code)
		if err != nil {
			return nil, err
		}
		return a.MenuBll.ConvToTreeData(menus, hasAction)
	}

	// 查询用户类型权限
	typeItem, err := a.UserTypeBll.GetByCode(userType)
	if err != nil {
		return nil, err
	} else if typeItem == nil || len(typeItem.RoleIDs) == 0 {
		return nil, nil
	}

	// 查询角色菜单ID列表
	menuIDs, err := a.RoleBll.QueryMenuIDsByIDs(typeItem.RoleIDs)
	if err != nil {
		return nil, err
	} else if len(menuIDs) == 0 {
		return nil, nil
	}

	menus, err := a.MenuBll.QueryBySystemCodeAndIDs(code, menuIDs)
	if err != nil {
		return nil, err
	}

	return a.MenuBll.ConvToTreeData(menus, hasAction)
}
